<template>
  <div class="card-bind">
    <el-tip>
      为了资金安全考虑，第一次绑定银行卡填写的姓名无法再次修改；最多绑定10张银行卡。
    </el-tip>
    <el-tip type="warning" v-if="bankData.cardList.length >= 10">
      若要添加新的银行卡，请先删除一张已绑定银行卡
    </el-tip>

    <el-form class="card-bind__form"
             :model="form"
             :rules="rules"
             @submit.native.prevent="bindCard"
             ref="form"
             :disabled="loading"
             size="medium"
             label-width="0.9rem"
             v-if="bankData.cardList.length < 10"
    >
      <el-form-item prop="name" label="姓名：" :rules="{required: true, message: '请输入银行卡持有人姓名'}">
        <!--<template v-if="user.reallyName">{{user.reallyName}}</template>-->
        <el-input v-model="form.name" v-if="user.reallyName" :value="user.reallyName" placeholder="请输入银行卡持有人姓名"></el-input>
        <el-input v-model="form.name" v-else></el-input>
      </el-form-item>
      <el-form-item label="银行卡号：" prop="cardNo" :error="formError">
        <el-input v-model="form.cardNo" placeholder="请输入银行卡号"></el-input>
      </el-form-item>
      <el-form-item no-spacing="">
        <!--<el-button type="primary" native-type="submit">确定</el-button>-->
        <el-button type="primary" @click="addCard(form.name,form.cardNo)">确定</el-button>
      </el-form-item>
    </el-form>
    <card-list :bank-data="bankData" @on-success="refresh"></card-list>
    <div v-transfer-dom>
      <el-dialog :visible.sync="dialogVisible" :before-close="() => {dialogVisible = false}" :title="dialogTitle"
                 :width="consts.DIALOG_SIZE_NORMAL">
        <component :is="dialogName"
                   @on-success="refresh"
                   :card-info="dialogProps"
                   v-if="dialogName"
        ></component>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  const cache = [];
  const requireAll = r => r.keys().forEach(key => cache[key] = r(key));
  const req = require.context('./misc', true, /\.png$/);
  requireAll(req);

  import CardAddbind from './card-addbind';
  import {factory, form, dialog} from '@/build';

  import {
    bankListApi as listApi,
    bankListBindApi as saveApi,
  } from "@/services/api/user";

  import CardList from "./card-list";

  export default {
    name: 'safety-card-bind',

    components: {CardList,CardAddbind},

    mixins: [form, dialog],

    inject: ['setViewName'],
    data(){
      return {
        bankData: {
          cardList: [],
          name: ''
        },
        form:{
          name: undefined,
          cardNo: undefined,
        },
        rules: {
          cardNo: factory.getRule('cardNumber'),
        },
        formError: undefined,
      };
    },
    computed: {
      ...mapState({
        user: state => state.user
      }),
      length() {
        return this.$refs.list.getCount();
      }
    },
    methods: {
      bindCard() {
        if (this.bankData.cardList.length < 10) {
          this.doSave({action: 'saveForm', form: 'form'});
        } else {
          this.$notify({
            title: '已超出最高10张银行卡绑卡限制，无法进行绑定！',
            // message: errorMessage,
            type: 'error',
            duration: 2000
          });
        }
      },
      // refresh() {
      //   this.getAll();
      // },
      addCard(name,cardNo) {
        this.$refs['form'].validate((valid) => {
          if(valid){
            const cardInfo = {"name":name,"cardNo":cardNo}
            this.openDialog({
              dialogName: 'card-addbind',
              props: cardInfo
            });
          }
        });

      },
      refresh() {
        this.getAll();
        this.dialogVisible = false;
        this.$emit('on-success');
      },
    },

    created() {
      this.setViewName('绑定银行卡');
      if(this.user.reallyName && !_.isEmpty(this.user.reallyName)){
        this.form.name = this.user.reallyName
      }
    },

    mounted() {
      this.bindGet(listApi, 'bankData', {
        format: (bankData) => {
          _.each(bankData.cardList, (bankInfo) => {
            const bankName = _.find(consts.BANK_LIST, {
              value: bankInfo.bankId
            }).name;
            bankInfo.name = bankName;
            bankInfo.pic = cache[`./${bankName}-small.png`];

          });
          return bankData;
        }
      });

      this.getAll();

      this.bindSave(saveApi, 'saveForm', 'form', {
        beforeSend: (data) => {

          this.formError = '';
          return data;
        },
        afterSuccess: () => {
          this.$store.dispatch(types.OAUTH);
          this.$store.dispatch(types.GET_SECURITY);

          //复原验证框
          this.refresh();
          this.form.cardNo = undefined;
        },
        afterFail: ([result, data]) => {
          this.formError = data.message;
        }
      });
    },

  };
</script>

<style lang="scss" scoped>
  @include b(card-bind) {

    .el-input {
      width: 380px;
    }
    .el-button {
      width: 260px;
    }

    @include e(form) {
      padding-bottom: 78px;
    }
  }
</style>
